from entity import migrate_pb2
import json


class MigrateConfig:
    """
    迁移配置
    """

    """
    sharing 分片后多线程模式插入
    single 分片后单线程模式插入
    """
    insert_mode = None

    """
    涉及的数据库表
    table_name = None
    条件
    condition = ''
    """
    tables = []

    original_url = ''  # 源数据库地址
    dest_url = ''  # 目标数据库地址

    def parse_url(self, connection_url):
        address = connection_url.split("/")[0]
        others = connection_url.split("/")[1]
        url = address.split(":")[0]
        port = address.split(":")[1]
        db = others.split("?")[0]
        configs = others.split("?")[1].split("&")
        config_map = {config.split("=")[0]: config.split("=")[1] for config in configs}
        username = config_map.get("username")
        password = config_map.get("password")

        return url, port, db, username, password


class DbClientService:
    sharding_info = []
    config = MigrateConfig()

    def generate_sharding(self, table):
        pass

    @staticmethod
    def parse(request: str):
        pass

    @staticmethod
    def generate_sharding():
        pass

    def get_sharding_result(self, sharding):
        pass

    def migrate(self, stub, db):
        for sharding in self.sharding_info:
            results = self.get_sharding_result(sharding)

            params = {}
            params['key'] = self.config.dest_url
            params['dest_url'] = self.config.dest_url
            params['data_list'] = results

            response = stub.send(migrate_pb2.Data(db=db, type='insert',
                                                  data=json.dumps(params, ensure_ascii=False)))  # 执行计算命令
            if response.message == 'ok':
                print("批次{}已经执行完毕".format(sharding['batch_num']))

    def show_create_table(self, stub, db):
        """
        获得建表语句
        :return:
        """
        pass


class DbServerService:
    config = MigrateConfig()

    def __init__(self,dest_url):
        pass

    def create_table(self,table_name,schema):
        pass

    def execute_sql(self):
        pass


if __name__ == "__main__":
    config = MigrateConfig()
    config.original_url = "192.168.20.209:3306/earring_activiti?useUnicode=true&characterEncoding=utf-8&username=root&password=Gc1IxKIkd1aVciFj"
    print(config.parse_url(config.original_url))
